import {StyleSheet, Text, TouchableOpacity, View, Image} from 'react-native'
import React, {useEffect, useState} from 'react'
import PageScrollView from "@/components/PageScrollView";
import PageTabBar from "@/components/PageTabBar";
import FcModal from '@/components/FcModal';
import DatePicker from '@/components/DatePicker';
import {router} from "expo-router";
import {Flex} from "@ant-design/react-native";

import {useGetTaskListQuery} from "@/store/api/videoPublish/videoPublishApi";

type Props = {}

const task = (props: Props) => {
  const [listParams, setListParams] = useState({
    pageNo: 1,
    pageSize: 20,
    pubStatus: '',
    createTime_begin: '',
    createTime_end: '',
  })
  const [taskList, setTaskList] = useState<any>([])
  const [imgOpen, setImgOpen] = useState(false)
  const [taskItem, setTaskItem] = useState<any>({})
  const [statusOpen, setStatusOpen] = useState<any>(false)
  const [dateOpen, setDateOpen] = useState(false)
  
  const statusList = [
    {
      label: '全部状态',
      value: ''
    },
    {
      label: '待发布',
      value: 0
    },
    {
      label: '成功',
      value: 1
    },
    {
      label: '失败',
      value: 2
    },
    {
      label: '暂停',
      value: 3
    },
  ]
  
  const {data:listDataRef,refetch:listRefetch} = useGetTaskListQuery(listParams)
  
  useEffect(() => {
    listRefetch();
  }, []);

  useEffect(() => {
    if(listDataRef?.code === 200){
      let list = listDataRef?.result?.records || []
      setTaskList(list)
    }
  },[listDataRef])

  const getFileAccessHttpUrl = (fileUrl:any, prefix = 'http') => {
    let result = fileUrl;
    let baseApiUrl:any = process.env.EXPO_PUBLIC_API_URL
    try {
      if (fileUrl && fileUrl.length > 0 && !fileUrl.startsWith(prefix)) {
        //判断是否是数组格式
        let isArray = fileUrl.indexOf('[') != -1;
        if (!isArray) {
          let prefix = baseApiUrl.includes('http://192.168.1.') ? `${baseApiUrl}/sys/common/static/` : `${baseApiUrl}/jeecgboot/sys/common/static/`;
          // 判断是否已包含前缀
          if (!fileUrl.startsWith(prefix)) {
            result = `${prefix}${fileUrl}`;
          }
        }
      }
    } catch (err) {}
    return result;
  };

  return (
    <PageScrollView
      isTransparentTab
      pageTab={
        <PageTabBar
          style={{marginVertical: 10}}
          title={'视频发布'}
          right={
            <TouchableOpacity style={{display: 'flex', flexDirection: 'row', alignItems: 'center'}} onPress={() => router.navigate(`/search`)}>
              <Text style={{fontFamily: 'FcIconFont', fontSize: 20, color: '#000000', marginRight: 3}}>&#xe641;</Text>
            </TouchableOpacity>
          }
          
        />
      }
      pageHeader={
        <Flex style={{paddingHorizontal: 16}}>
          <TouchableOpacity style={{width: '23%'}} onPress={() => setStatusOpen(true)}>
            <Flex justify='center' style={styles.search_item}>
              <Text style={styles.search_item_text} numberOfLines={1}>
                {statusList.find((val:any) => val.value === listParams.pubStatus)?.label ||'发布状态'}
              </Text>
              <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: 'rgba(0, 0, 0, 0.5)'}}>&#xe647;</Text>
            </Flex>
          </TouchableOpacity>

          <TouchableOpacity style={{width: '23%'}} onPress={() => setDateOpen(true)}>
            <Flex justify='center' style={styles.search_item}>
              <Text style={styles.search_item_text} numberOfLines={1}>创建时间</Text>
              <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: 'rgba(0, 0, 0, 0.5)'}}>&#xe647;</Text>
            </Flex>
          </TouchableOpacity>
        </Flex>
      }
    >
      <View>
        {
          taskList.map((item:any, index:any) => (
            <View style={styles.task_item} key={index}>
              <Flex align='start'>
                <View style={{width: 80,height: 125, marginRight: 10, position: 'relative', backgroundColor: '#ccc', borderRadius: 8}}>
                  <TouchableOpacity style={{flex: 1}} onPress={() => {setTaskItem(item); setImgOpen(true)}}>
                    <Image style={{width: '100%',height: '100%', borderRadius: 8}} source={{uri: getFileAccessHttpUrl(item.coverImagePath)}} resizeMode={'cover'}></Image>
                  </TouchableOpacity>
                  
                  <Flex style={{position: 'absolute', left: 10, bottom: 10, zIndex: 10}}>
                    {
                      item.sourcePlatform == 'douyin' ?
                      <Text style={{fontFamily: 'FcIconFont', fontSize: 12, marginRight: 3}}>&#xe676;</Text>
                      :
                      <View style={styles.ks_icon}>
                        <Text style={{fontFamily: 'FcIconFont', fontSize: 10, color: '#FFF'}}>&#xe89b;</Text>
                      </View>
                    }
                    <Text style={{color: '#FFF', fontSize: 10}}>{ item.sourcePlatform == 'douyin' ? '抖音' : '快手' }</Text>
                  </Flex>
                </View>
                <View style={{flex: 1}}>
                  <Flex style={{marginBottom: 3}}>
                    <Text style={[styles.task_item_status, item.pubStatus == 1 ? styles.text_green : item.pubStatus == 2 ? styles.text_pink : styles.text_gold]}>
                      { item.pubStatus == 0 ? '待发布' : item.pubStatus == 1 ? '发布成功' : item.pubStatus == 2 ? '发布失败' : '已暂停' }
                    </Text>
                    <Text style={{flex: 1}} numberOfLines={1} ellipsizeMode={'middle'}>{ item.originName }</Text>
                  </Flex>
                  <Flex>
                    <Text style={styles.task_item_label}>发布账号：</Text>
                    <Text style={styles.task_item_Value} numberOfLines={1}>{ item.nickname }</Text>
                  </Flex>
                  <Flex>
                    <Text style={styles.task_item_label}>发布类型：</Text>
                    <Text style={styles.task_item_Value}>{ item.pubTimeType == 0 ? '立即发布' : '定时发布' }</Text>
                  </Flex>
                  <Flex>
                    <Text style={styles.task_item_label}>创建时间：</Text>
                    <Text style={styles.task_item_Value}>{ item.createTime }</Text>
                  </Flex>
                  <Flex>
                    <Text style={styles.task_item_label}>发布时间：</Text>
                    <Text style={styles.task_item_Value}>{ item.pubTime || '--' }</Text>
                  </Flex>
                  <Flex>
                    <Text style={styles.task_item_label}>失败原因：</Text>
                    <Text style={styles.task_item_Value} numberOfLines={1}>{ item.pubMessage || '--' }</Text>
                  </Flex>
                </View>
              </Flex>
            </View>
          ))
        }
        

        {/* 发布状态弹窗 */}
        <FcModal
          isOpen={statusOpen}
          onFcModalClose={() => setStatusOpen(false)}
          titleText='分组标签'
          titleBottomBorderWidth={1}
        >
          <View>
            {statusList.map((item:any, index:any) => (
              <TouchableOpacity key={index} style={[styles.modal_item_text]} onPress={() => {setStatusOpen(false); setListParams({...listParams, pageNo: 1, pubStatus: item.value}); listRefetch()}}>
                <Text style={{fontSize: 15, color: listParams.pubStatus === item.value ? '#2856FF' : ''}}>{item.label}</Text>
              </TouchableOpacity>
            ))}
          </View>
        </FcModal>

        {/* 日期弹窗 */}
        <DatePicker
          isOpen={dateOpen} 
          titleText={'编写日期'} 
          dateRange={[listParams.createTime_begin, listParams.createTime_end]}
          dateType='range'
          onClose={() => setDateOpen(false)}
          onConfirm={(startDate:any, endDate:any) => {setListParams({...listParams, pageNo: 1, createTime_begin: startDate, createTime_end: endDate}); listRefetch()}}
        ></DatePicker>

        {/* 图片弹窗 */}
        <FcModal
          isOpen={imgOpen}
          transparent
          closeShow={true}
          animationType='fade'
          onFcModalClose={() => setImgOpen(false)}
          style={{width: 300, borderBottomRightRadius: 12, borderBottomLeftRadius: 12}}
          titleBottomBorderWidth={0}
        >
          <Image style={{height: 500, borderRadius: 8}} source={{uri: getFileAccessHttpUrl(taskItem.coverImagePath)}} resizeMode={'cover'}></Image>
        </FcModal>
      </View>
    </PageScrollView>
  )
}

export default task

const styles = StyleSheet.create({
  task_item: {
    padding: 12,
    backgroundColor: '#FFF',
    borderRadius: 8,
    marginTop: 12,
  },
  task_item_status: {
    width: 52,
    minWidth: 52,
    height: 18,
    fontSize: 10,
    borderRadius: 4,
    marginRight: 8,
    textAlign: 'center',
    lineHeight: 18,
  },
  text_green: {
    color: '#07C160',
    backgroundColor: 'rgba(7, 193, 96, 0.1)',
  },
  text_pink: {
    color: '#FA5151',
    backgroundColor: 'rgba(250, 81, 81, 0.1)',
  },
  text_gold: {
    color: '#FF9D00',
    backgroundColor: 'rgba(255, 157, 0, 0.1)',
  },
  task_item_label: {
    fontSize: 12,
    lineHeight: 22,
    color: 'rgba(0, 0, 0, 0.3)',
  },
  task_item_Value: {
    fontSize: 12,
    lineHeight: 22,
    color: 'rgba(0, 0, 0, 0.5)',
    flex: 1
  },
  ks_icon: {
    width: 14, 
    height: 14, 
    borderRadius: '50%', 
    backgroundColor: '#F74E18',
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 3,
  },
  search_item: {
    height: 28,
    borderRadius: 4,
    marginRight: 8,
    backgroundColor: '#F1F2F4',
  },
  search_item_text: {
    color: 'rgba(0, 0, 0, 0.5)',
    fontSize: 12,
    marginLeft: 2,
    maxWidth: '85%',
  },
  modal_item_text: {
    marginHorizontal: 16,
    height: 56,
    alignItems: 'center',
    justifyContent: 'center',
    borderBottomColor: 'rgba(0,0,0,0.05)',
    borderBottomWidth: 1,
    fontSize: 17,
    color: 'rgba(0,0,0,0.9)'
  },
})